function x = setinfnantomean(x, dim, t)
% setinfnantomean  - set Inf/NaN in input to mean (over dim)
%
% FORMAT:       x = setinfnantomean(x [, dim [, t]])
%
% Input fields:
%
%       x           data
%       dim         optional dimension, default: 1st non-singleton
%       t           threshold (if more than t Inf/NaN values, set all to 0)
%                   whereas t can be 0...1 (relative) 1...N absolute or
%                   special value 's' for >= sqrt(size(x,dim))
%
% Output fields:
%
%       x           data with Inf/NaN values replaced by mean over dim

% Version:  v0.7g
% Build:    9040116
% Date:     Apr-01 2009, 4:27 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
   ~isnumeric(x)
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing first argument.' ...
    );
end
if nargin < 2 || ...
   ~isa(dim, 'double') || ...
    numel(dim) ~= 1 || ...
    isinf(dim) || ...
    isnan(dim) || ...
    dim < 1 || ...
    dim > ndims(x)
    dim = findfirst(size(x) > 1);
    if isempty(dim)
        dim = 1;
    end
end

% get mean over dim
[m, ge] = meannoinfnan(x, dim);

% replicate along dim
xnd = ndims(x);
rsz = ones(1, xnd);
rsz(dim) = size(x, dim);
m = repmat(m, rsz);
x(~ge) = m(~ge);

% threshold number of Inf/NaN values?
if nargin > 2 && ...
    numel(t) == 1 && ...
   ((isa(t, 'double') && ...
    ~isinf(t) && ...
    ~isnan(t) && ...
     t >= 0 && ...
     t <= size(x, dim)) || ...
    (ischar(t) && ...
     lower(t) == 's'))
    if ischar(t)
        t = sqrt(size(x, dim));
    elseif t < 1
        t = t * size(x, dim);
    end
    ge = repmat(sum(~ge, dim, 'double') >= t, rsz);
    x(ge) = 0;
end
